package com.pine.manager.pineframework.trigger.impl;

import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysRoleUpdateStatusRequest;
import com.pine.common.trigger.AbstractTriggerTemplate;
import com.pine.common.trigger.TriggerContext;
import com.pine.dao.pineframework.constants.StatusEnum;
import com.pine.dao.pineframework.entity.SysRole;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.SysRoleManager;
import com.pine.manager.pineframework.bo.SysRoleBo;
import com.pine.manager.pineframework.convertors.SysRoleConvertor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 系统角色表修改状态 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-16
 */
@Component
@Slf4j
public class SysRoleUpdateStatusTrigger extends AbstractTriggerTemplate<SysRoleUpdateStatusRequest, Boolean> {

    @Resource
    private SysRoleManager sysRoleManager;
    @Resource
    private SysRoleConvertor sysRoleConvertor;

    private SysRoleBo oldSysRoleBo;

    public SysRoleUpdateStatusTrigger() {
        super(TriggerTypeEnum.SYS_ROLE_UPDATE_STATUS);
    }

    @Override
    protected void before(TriggerContext<SysRoleUpdateStatusRequest> triggerContext) {
        SysRoleUpdateStatusRequest request = triggerContext.getTriggerRequest();
        Long roleId = request.getId();
        oldSysRoleBo = sysRoleManager.getOneByUniqueKey(roleId, SysRole::getId);
        if (Objects.isNull(oldSysRoleBo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_ROLE_NOT_EXIST);
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean trigger(TriggerContext<SysRoleUpdateStatusRequest> triggerContext) {
        // 设置状态
        SysRoleUpdateStatusRequest request = triggerContext.getTriggerRequest();
        oldSysRoleBo.setStatus(StatusEnum.of(request.getStatus()));

        // 修改数据库
        SysRole sysRole = sysRoleConvertor.entityBoToEntity(oldSysRoleBo);
        return sysRoleManager.updateById(sysRole);
    }
}
